import { createUserAdmin, getUserListAdmin, editUserAdmin, deleteUserAdmin, recoverUserAdmin } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Modal, ModalHeader, ModalBody, Form, Label, Button, ButtonGroup, UncontrolledDropdown, DropdownToggle, DropdownItem, DropdownMenu } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';

const AdminUserListPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;

  const [cartList, setCartList] = useState([]);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const [isOpen, setIsOpen] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [pageCount, setPageCount] = useState(1);
  const [keyword, setKeyword] = useState("");
  const [addUserModal, setAddUserModal] = useState(false);
  const [filter, setFilter] = useState(-1);

  const [deleteId, setDeleteId] = useState("");
  const [confirmModel, setConfirmModel] = useState(false);

  const [recoverId, setRecoverId] = useState("");
  const [recoverModel, setRecoverModel] = useState("");

  const debounceRef = useRef(null);
  const router = useRouter();

  const [formData, setFormData] = useState({
    "email_adress": "",
    "nick_name": "",
    "adress": "",
    "zip_code": "",
    "user_group_id": "",
    "password": "",
    "phone_number": ""
  });

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getUserListAdmin({
          "keyword": "",
          "filter": filter.toString(),
          "pageNum": 1,
          "pageSize": 10
        }).then(res => {
          setList(res.data);
          setPageCount(res.page_count);
        })
        // getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
        //   setCartList(res.data);
        //   let to = Number(0);
        //   var qtys = [];
        //   res.data.map(item => {
        //     to += parseFloat(item.price * item.quantity);
        //     qtys.push({
        //       "product_id": item.product_id,
        //       "quantity": item.quantity,
        //       "product_stock": item.product_stock,
        //       "price": item.price
        //     })
        //   })
        //   setTotal(getTwoDecimal(`${to}`));
        //   setQtyList(qtys);
        // });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var user = localStorage.getItem("XYCLogin")
    if (!user) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

  }, [])

  const handleQtyUpdate = (item, quantity) => {
    if (quantity > 0 && quantity) {
      debounceRef.current(item, quantity);
      var newQtys = [];
      qtyList.map(q => {
        if (q.product_id != item.product_id)
          newQtys.push(q);
      });
      newQtys.push({
        "product_id": item.product_id,
        "quantity": quantity,
        "product_stock": item.product_stock,
        "price": item.price
      });
      setQtyList(newQtys);

      var newTotal = 0;
      newQtys.map(nq => {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      })
      setTotal(getTwoDecimal(`${newTotal}`))
    }
  };

  const removeProduct = (item) => {
    setCartList(v => v.filter(p => p.product_id != item.product_id));
    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
    var newTotal = 0;
    qtyList.map(nq => {
      if (nq.product_id != item.product_id) {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      }
    })
    setQtyList(v => v.filter(p => p.product_id != item.product_id));
    console.log(newTotal)
    setTotal(getTwoDecimal(`${newTotal}`))
  }

  const AddPage = () => {
    if (pageNum < pageCount) {
      getUserListAdmin({
        "keyword": keyword,
        "filter": filter.toString(),
        "pageNum": pageNum + 1,
        "pageSize": 10
      }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      })
      setPageNum(pageNum + 1);
    }
  }

  const SearchProduct = () => {
    getUserListAdmin({
      "keyword": keyword,
      "filter": filter.toString(),
      "pageNum": "1",
      "pageSize": "10"
    }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }

  const onKeywordChange = (e) => {
    setKeyword(e.target.value);
  }

  const MinusPage = () => {
    if (pageNum > 1) {
      getUserListAdmin({
        "keyword": keyword,
        "filter": filter.toString(),
        "pageNum": pageNum - 1,
        "pageSize": 10
      }).then(res => {
        setList(res.data);
        setPageCount(res.page_count)
      })
      setPageNum(pageNum - 1);
    }
  }

  const EditUserInfo = (item) => {
    setIsOpen(true);
    setFormData({
      "email_adress": item.email_adress,
      "nick_name": item.nick_name,
      "adress": item.deliver_adress,
      "zip_code": item.zip_code,
      "user_group_id": item.user_group_id,
      "password": "",
      "phone_number": item.phone_number
    })
  }

  const FormDataChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  }

  const SaveChange = () => {
    if ((formData.nick_name.length > 0 && formData.nick_name.length < 20)
      && (formData.adress.length > 0 && formData.adress.length < 50)
      && (formData.zip_code.length > 0 && formData.zip_code.length < 20)
      && (formData.phone_number.length > 0 && formData.phone_number.length < 20)) {
      editUserAdmin({
        "email_adress": formData.email_adress,
        "nick_name": formData.nick_name,
        "adress": formData.adress,
        "zip_code": formData.zip_code,
        "user_group_id": formData.user_group_id,
        "password": formData.password,
        "phone_number": formData.phone_number
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Update User Succeed.");
          location.reload();
        }
        else {
          toast.error(res.msg);
        }
      })
    }
    else {
      toast.warning("Form Can not be null.")
    }
  }

  const SaveAddUser = () => {
    if ((formData.nick_name.length > 0 && formData.nick_name.length < 20)
      && (formData.adress.length > 0 && formData.adress.length < 50)
      && (formData.zip_code.length > 0 && formData.zip_code.length < 20)
      && (formData.phone_number.length > 0 && formData.phone_number.length < 20)
      && (formData.password.length > 0 && formData.password.length < 20)
      && (formData.email_adress.length > 0 && formData.email_adress.length < 20)) {
      createUserAdmin({
        "email_adress": formData.email_adress,
        "nick_name": formData.nick_name,
        "adress": formData.adress,
        "zip_code": formData.zip_code,
        "user_group_id": formData.user_group_id,
        "password": formData.password,
        "phone_number": formData.phone_number
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Create User Succeed.");
          location.reload();
        }
        else {
          toast.error(res.msg);
        }
      })
    }
    else {
      toast.warning("Form Validate Error.")
    }
  }

  const AddUser = () => {
    setAddUserModal(true);
    setFormData({
      "email_adress": "",
      "nick_name": "",
      "adress": "",
      "zip_code": "",
      "user_group_id": "0",
      "password": "",
      "phone_number": ""
    });
  }

  const ChangeFilter = (filterNum) => {
    setFilter(filterNum);
    getUserListAdmin({
      "keyword": keyword,
      "filter": `${filterNum}`,
      "pageNum": `${pageNum}`,
      "pageSize": "10"
    }).then(res => {
      setList(res.data);
      setPageCount(res.page_count)
    });
  }

  const DeleteUser = (id) => {
    deleteUserAdmin({
      id: id
    }).then(res => {
      if (res.error_code == "2000") {
        toast.success("Delete Succeed.");
        location.reload();
      }
      else {
        toast.error(res.msg);
      }
    })
  }

  const RecoverUser = () => {
    recoverUserAdmin({ id: `${recoverId}` }).then(res => {
      if (res.error_code == "2000") {
        toast.success("Recover Succeed.");
        location.reload();
      }
      else {
        toast.error(res.msg);
      }
    })
  }

  return (
    <div>
      <Modal isOpen={recoverModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to recover user?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setRecoverModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { RecoverUser() }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>

      <Modal isOpen={confirmModel} centered size="lg" style={{ width: 350 }}>
        <ModalHeader >Confirm</ModalHeader>
        <ModalBody>
          <Row>
            <div style={{ marginLeft: 40, marginTop: 20 }}>
              <h3>Confirm to delete user?</h3>
            </div>
          </Row>
          <Row>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setConfirmModel(false) }}>Cancel</Button>
              </div>
            </Col>
            <Col md="6">
              <div className="checkout-form">
                <Button style={{ width: "100%", marginTop: 20 }} color="primary" onClick={() => { DeleteUser(deleteId) }}>Confirm</Button>
              </div>
            </Col>
          </Row>
        </ModalBody>
      </Modal>
      <Modal isOpen={addUserModal} centered size="lg">
        <ModalHeader >User Info
        </ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col md="6">
                      <Label for="nick_name">Email Adress</Label>
                      <Input type="text" className="form-control" invalid={(formData.email_adress == "")} id="email_adress" name="email_adress" placeholder="Email Adress" onChange={FormDataChange} />
                    </Col>
                    <Col md="6">
                      <Label for="nick_name">Nick Name</Label>
                      <Input type="text" className="form-control" invalid={(formData.nick_name == "")} id="nick_name" name="nick_name" placeholder="Nick Name"
                        onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="6">
                      <Label for="adress">Address</Label>
                      <Input type="text" className="form-control" id="adress" invalid={(formData.adress == "")} name="adress" placeholder="Deliver Address"
                        required="" onChange={FormDataChange} />
                    </Col>
                    <Col md="6">
                      <Label for="zip_code">Zip Code</Label>
                      <Input type="text" className="form-control" id="zip_code" invalid={(formData.zip_code == "")} name="zip_code" placeholder="zip-code"
                        required="" onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="3">
                      <Label for="phone_number">Phone Number</Label>
                      <Input type="text" className="form-control" id="phone_number" name="phone_number" placeholder="Phone Number"
                        onChange={FormDataChange} />
                    </Col>
                    <Col md="3">
                      <Label for="user_group_id">User Group</Label>
                      <div>
                        <Input
                          id="user_group_id"
                          name="user_group_id"
                          type="select"
                          style={{ width: 150, height: 35 }}
                          defaultValue={0}
                          onChange={FormDataChange}
                        >
                          <option value="0">
                            Normal
                          </option>
                          <option value="1">
                            Admin
                          </option>
                        </Input>
                      </div>
                    </Col>
                    <Col md="6">
                      <Label for="password">Password</Label>
                      <Input type="text" invalid={(formData.password == "")} className="form-control" id="password" name="password" placeholder="change password" onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="6">
                      </Col>
                      <Col md="3">
                        <Button href={null} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} color="primary" onClick={SaveAddUser} >Save</Button>
                      </Col>
                      <Col md="3">
                        <Button href={null} onClick={() => { setAddUserModal(false) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} >Cancel</Button>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>

      <Modal isOpen={isOpen} centered size="lg">
        <ModalHeader >User Info
        </ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col md="6">
                      <Label for="nick_name">Email Adress</Label>
                      <Input type="text" className="form-control" id="email_adress" name="email_adress" placeholder="Email Adress" disabled value={formData.email_adress} />
                    </Col>
                    <Col md="6">
                      <Label for="nick_name">Nick Name</Label>
                      <Input type="text" className="form-control" id="nick_name" name="nick_name" placeholder="Nick Name" invalid={(formData.nick_name == "")}
                        defaultValue={formData.nick_name} onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="6">
                      <Label for="adress">Address</Label>
                      <Input type="text" className="form-control" id="adress" name="adress" placeholder="Deliver Address" invalid={(formData.adress == "")}
                        required="" defaultValue={formData.adress} onChange={FormDataChange} />
                    </Col>
                    <Col md="6">
                      <Label for="zipCode">Zip Code</Label>
                      <Input type="text" className="form-control" id="zip_code" name="zip_code" placeholder="zip-code" defaultValue={formData.zip_code} invalid={(formData.zip_code == "")}
                        required="" onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="3">
                      <Label for="phone_number">Phone Number</Label>
                      <Input type="text" className="form-control" id="phone_number" name="phone_number" placeholder="Phone Number" defaultValue={formData.phone_number}
                        onChange={FormDataChange} />
                    </Col>
                    <Col md="3">
                      <Label for="user_group_id">User Group</Label>
                      <div>
                        <Input
                          id="user_group_id"
                          name="user_group_id"
                          type="select"
                          style={{ width: 150, height: 35 }}
                          defaultValue={formData.user_group_id}
                          onChange={FormDataChange}
                        >
                          <option value="0">
                            Normal
                          </option>
                          <option value="1">
                            Admin
                          </option>
                        </Input>
                      </div>
                    </Col>
                    <Col md="6">
                      <Label for="password">Password</Label>
                      <Input type="text" className="form-control" id="password" name="password" placeholder="change password" onChange={FormDataChange} />
                    </Col>
                  </Row>
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="6">
                      </Col>
                      <Col md="3">
                        <Button href={null} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} color="primary" onClick={SaveChange} >Save</Button>
                      </Col>
                      <Col md="3">
                        <Button href={null} onClick={() => { setIsOpen(false) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} >Cancel</Button>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      {/* <div>
        <Row className="admin-user-btn-list">
          <Col md="3"><Input type="text" className="form-control" id="lname" name="lname" placeholder="Please enter Email or user name" onChange={onKeywordChange} /></Col>
          <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={SearchProduct} >Search</a></Col>
          <Col md="1"><a href={null} style={{ width: 130, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={AddUser} >Add User</a></Col>
        </Row>
      </div> */}
      <div>
        <Row className="order-list-filter-btn-list">
          <Col md="4">
            <ButtonGroup style={{ marginRight: 20, marginLeft: 80 }}>
              <UncontrolledDropdown>
                <DropdownToggle caret>
                  Filter
                </DropdownToggle>
                <DropdownMenu>
                  <DropdownItem active={filter == '-1'} onClick={() => { ChangeFilter(-1) }}>
                    All
                  </DropdownItem>
                  <DropdownItem active={filter == '-2'} onClick={() => { ChangeFilter(-2) }}>
                    Deleted
                  </DropdownItem>
                </DropdownMenu>
              </UncontrolledDropdown>
            </ButtonGroup>
          </Col>
          <Col md="3">
          </Col>
          <Col md="2"><Input type="text" className="form-control" id="lname" name="lname" placeholder="Please enter Email or user name" onChange={onKeywordChange} /></Col>
          <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={SearchProduct} >Search</a></Col>
          <Col md="2"><a href={null} style={{ width: 130, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" onClick={AddUser} >Add User</a></Col>
        </Row>
      </div>
      {list && list.length > 0 ? (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <table className="table cart-table table-responsive-xs">
                  <thead>
                    <tr className="table-head">
                      {/* <th scope="col">image</th> */}
                      <th scope="col">user id</th>
                      <th scope="col">Email Adress</th>
                      <th scope="col">user name</th>
                      <th scope="col">user group</th>
                      <th scope="col">action</th>
                    </tr>
                  </thead>
                  {list.map((item, index) => {
                    return (
                      <tbody key={index}>
                        <tr>
                          <td>
                            <a>{item.user_id}</a>
                          </td>
                          <td>
                            {item.email_adress}
                          </td>
                          <td>
                            <div>
                              <div>
                                <h4>{item.nick_name}</h4>
                              </div>
                            </div>
                          </td>
                          <td>
                            <h4>
                              {item.user_group_desc}
                            </h4>
                          </td>
                          <td>
                            {
                              filter != '-2' &&
                              (
                                <Button className="admin-user-acion" onClick={() => { EditUserInfo(item) }}>Edit</Button>
                              )
                            }
                            {
                              filter != '-2' &&
                              (
                                <Button className="admin-user-acion" onClick={() => { setConfirmModel(true); setDeleteId(item.user_id); }}>Delete</Button>
                              )
                            }
                            {
                              filter == '-2' &&
                              (
                                <Button className="admin-user-acion" onClick={() => { setRecoverModel(true); setRecoverId(item.user_id); }}>Recover</Button>
                              )
                            }
                          </td>
                        </tr>
                      </tbody>
                    );
                  })}
                </table>
              </Col>
            </Row>
          </Container>
          <div className="admin-page-select-btn">
            <Button className="page-select-btn1" onClick={MinusPage}>Last Page</Button><span className="page-select-label">{pageNum} IN {pageCount}</span><Button className="page-select-btn2" onClick={AddPage}>Next Page</Button>
          </div>
        </section>
      ) : (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <div>
                  <div className="col-sm-12 empty-cart-cls text-center">
                    <Media
                      src={cart}
                      className="img-fluid mb-4 mx-auto"
                      alt=""
                    />
                    <h3>
                      <strong>User List is Empty</strong>
                    </h3>
                    <h4>Add New User.</h4>
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>
      )}
    </div>
  );
};

export default AdminUserListPage;
